// 访问 token 缓存的 key
const TOKEN_KEY = "token";

export default {
  set(key: string, value: unknown) {
    if (typeof value === "undefined") {
      throw new Error(`不能设置 ${key} 的值为 undefined`);
    }
    localStorage.setItem(key, JSON.stringify(value));
  },
  get(key: string) {
    const value = localStorage.getItem(key) as string | null | undefined;
    if (value === null || value === undefined) {
      return null;
    }
    return JSON.parse(value);
  },
  remove(key: string) {
    return localStorage.removeItem(key);
  },
  clear() {
    return localStorage.clear();
  },
  getAllKeys() {
    return Reflect.ownKeys(localStorage);
  },
  has(key: string) {
    return Reflect.has(localStorage, key);
  },
  // 设置token
  setToken(value: unknown) {
    this.set(TOKEN_KEY, value);
  },
  clearToken() {
    this.remove(TOKEN_KEY);
  },
  getAccessToken() {
    return this.get(TOKEN_KEY)?.accessToken;
  },
  getRefreshToken() {
    return this.get(TOKEN_KEY)?.refreshToken;
  },
};
